package com.example.market2023.controller;

import com.example.market2023.entity.Suppliers;
import com.example.market2023.service.SuppliersService;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
public class SuppliersController {
    @Autowired
    SuppliersService suppliersService;
    @Autowired
    HttpServletRequest request;

    @RequestMapping("/suppliers")
    public String suppliers(Model model){

        //查询结果用model绑定 如何传递到前端
        Object username = request.getSession().getAttribute("username");
//        首先判断session里面是否有用户，如果有用户的值就直接用户登录，如果没有用户的值就没有登录
//        后续的操作就不允许访问要先登陆才能访问
        if (username==null){
            return "redirect:/";
        }else{
            //调用service方法查询商品列表 数据库的数据
            List<Suppliers> suppliers = suppliersService.findAll();
            model.addAttribute("data",suppliers);
            model.addAttribute("username",username);
            System.out.println(suppliers);
            //返回到suppliers窗体页面
            return "suppliers";
        }
    }

    @RequestMapping("/suppliersAdd")
    public String suppliersAdd(Model model){
        Object username = request.getSession().getAttribute("username");
        if (username==null){
            return "redirect:/";
        }else{
            model.addAttribute("username",username);
            return "suppliersAdd";
        }

    }

    @RequestMapping("/suppliersAddProcess")
    public String suppliersAddProcess(@RequestParam String name, @RequestParam String addr, @RequestParam String phone){

        //组装一个实体对象
        Suppliers suppliers=new Suppliers();
        suppliers.setName(name);
        suppliers.setAddr(addr);
        suppliers.setPhone(phone);

        //调用service的add方法给数据库
        if (suppliersService.add(suppliers)==1){
            return "redirect:/suppliers";
        }else {
            return "redirect:/suppliers";
        }

    }

    @RequestMapping("/suppliersUpdate")
    public String suppliersUpdate(@RequestParam String id,Model model){

        Object username = request.getSession().getAttribute("username");
        if (username==null){
            return "redirect:/";
        }else{
//        首先基于id查询出来该id记录里的所有数据信息
            Suppliers suppliers=new Suppliers();
            suppliers.setId(Integer.valueOf(id));
//        调用service方法查询出来该记录的数据信息
            Suppliers suppliers1=suppliersService.findOne(suppliers);
//        2.将这些数据信息返回给视图
            model.addAttribute("data",suppliers1);
            model.addAttribute("username",username);
//        3.返回视图文件
            return "suppliersUpdate";
        }

    }


}
